package JAVA300.第十章IO;

import java.io.*;

/**
 * 综合应用
 * 图片读到字节数组
 * 字节数组到文件
 */

public class IO_Study08 {
    public static void main(String[] args) {

        byte[] datas = FileToByteArray("testpic.png");
        System.out.println(datas.length);

        ByteArrayToFile(datas,"testpic-ByteArrayCopy.png");

    }

    //1.图片入到程序出道字节数组
    public static byte[] FileToByteArray(String filePath){
        File file = new File(filePath);

        byte[] dest = null;
        InputStream is = null;
        ByteArrayOutputStream baos =  null;

        try {
            is = new FileInputStream(file);
            baos = new ByteArrayOutputStream();

            int len =-1;
            byte[] flush = new byte[1024*10];
            while ((len = is.read(flush)) != -1){//从file里读入
                //output到字节数组
                baos.write(flush,0,len);

            }
            baos.flush();

            return baos.toByteArray();//进行返回
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return null;
    }

    //2.从字节数组到程序到文件
    public static void ByteArrayToFile(byte[] datas,String destPath){

        InputStream is = null;
        OutputStream os = null;

        try {
            is = new ByteArrayInputStream(datas);
            os = new FileOutputStream(new File(destPath));

            int len =-1;
            byte[] flush = new byte[1024*10];
            while ((len = is.read(flush)) != -1){
                os.write(flush,0,len);

            }
            os.flush();

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
